import { Computed, Mut, VueService } from "vue3-oop";
import type { FormData, WidgetItem, WidgetType } from "./index";

export default class WidgetNode extends VueService {
  
  @Mut() formData: FormData;
  @Mut() parentId: string | undefined;
  @Mut() widgetId: string;
  @Mut() type: WidgetType;
  @Mut() widgetItem: WidgetItem;
  @Mut() children = [] as WidgetNode[];

  constructor(
    formData: FormData,
    parentId: string | undefined,
    widgetId: string,
    type: WidgetType,
    widgetItem: WidgetItem
  ) {
    super();
    this.formData = formData;
    this.parentId = parentId;
    this.widgetId = widgetId;
    this.type = type;
    this.widgetItem = widgetItem;
  }

  /** 父节点 */
  @Computed() get parentWidgetNode(){
    return this.formData.nodeMap.get(this.parentId as string);
  }

  /** 判断本节点是否选中 */
  isSelected=():boolean=>{
    return this.formData.isSelectedWidgetId(this.widgetId)
  }

  /** 设置本节点选中 */
  setSelected=():void=>{
    this.formData.setSelectedWidgetId(this.widgetId);
  }

  /** 设置父节点选中 */
  setParentSelected=():void=>{
    this.formData.setSelectedWidgetId(this.parentId as string);
  }

  /**
   * 将子节点向前移动一位
   * @param widgetId 子节点ID
   */
  moveChildNodeFoward=(widgetId:string):void=>{
    for(let i=1;i<this.children.length;i++){
      if (this.children[i].widgetId === widgetId) {
        let tmp = this.children[i - 1];
        this.children[i - 1] = this.children[i];
        this.children[i] = tmp;
        break;
      }
    }
  }

  /**
   * 将本节点向前移动一位 
   */
  moveFoward=():void=>{
    this.parentWidgetNode?.moveChildNodeFoward(this.widgetId);
  }

  /**
   * 将子节点向后移动一位
   * @param widgetId 子节点ID
   */
  moveChildNodeBackwards=(widgetId:string):void=>{
    for (let i = 0; i < this.children.length - 1; i++) {
      if (this.children[i].widgetId === widgetId) {
        let tmp = this.children[i + 1];
        this.children[i + 1] = this.children[i];
        this.children[i] = tmp;
        break;
      }
    }
  }

  /**
   * 将本节点向后移动一位
   */
  moveBackwards=()=>{
    this.parentWidgetNode?.moveChildNodeBackwards(this.widgetId);
  }

  /**
   * 删除子节点
   * @param widgetId 子节点ID 
   */
   removeChildNode=(widgetId:string):void=>{
    this.children = this.children.filter((childNode)=>childNode.widgetId!==widgetId);
    this.formData.nodeMap.delete(widgetId);
  }

  /**
   * 删除本节点
   */
  remove=()=>{
    this.parentWidgetNode?.removeChildNode(this.widgetId);
  }
}